﻿//垂直高度测量
function MeasurementVd() {
    var colorAll = {
        "point": sgworld.cesium.Color.fromCssColorString('#ff0000'),
        "polyline": sgworld.cesium.Color.fromCssColorString('#ffff00')
    };
    var spaceD_polyline = sgworld.Command.execute(0, 5, colorAll, function () {
        //sgworld._Viewer.scene.globe.depthTestAgainstTerrain = false;
    });
}
//海拔高度测量
function MeasurementAltitude() {
    var colorAll = {
        "point": sgworld.cesium.Color.fromCssColorString('#ff0000'),
        "polyline": sgworld.cesium.Color.fromCssColorString('#ffff00')
    };
    var spaceD_polyline = sgworld.Command.execute(1, 11, colorAll, function () {
        sgworld._Viewer.scene.globe.depthTestAgainstTerrain = false;
    });
}
//三维表积量测
function MeasurementThreeDSurfaceArea() {
    var colorAll = {
        "point": sgworld.cesium.Color.fromCssColorString('#ff0000'),
        "polyline": sgworld.cesium.Color.fromCssColorString('#ffff00'),
        'polygon': sgworld.cesium.Color.fromCssColorString('#ffff00')
    };
    sgworld._Viewer.scene.globe.depthTestAgainstTerrain = true;
    var SWPolygon_Area = sgworld.Command.execute(0, 8, colorAll, function () {
        sgworld._Viewer.scene.globe.depthTestAgainstTerrain = false;
    });
}
//平面面积量测
function MeasurementPlaneArea() {
    var colorAll = {
        "point": sgworld.cesium.Color.fromCssColorString('#ff0000'),
        "polyline": sgworld.cesium.Color.fromCssColorString('#ffff00'),
        'polygon': sgworld.cesium.Color.fromCssColorString('#ffff00')
    };
    var PlanePolygon_Area = sgworld.Command.execute(0, 3, colorAll, function () {
        sgworld._Viewer.scene.globe.depthTestAgainstTerrain = false;
    });
}
//角度量测
function MeasurementAngle() {
    var colorAll = {
        "point": sgworld.cesium.Color.fromCssColorString('#ff0000'),
        "polyline": sgworld.cesium.Color.fromCssColorString('#ffff00')
    };
    sgworld._Viewer.scene.globe.depthTestAgainstTerrain = true;
    var PlanePolygon_Area = sgworld.Command.execute(0, 9, colorAll, function () {
        sgworld._Viewer.scene.globe.depthTestAgainstTerrain = false;
    });
}
//空间距离测量
function MeasurementSpaceD() {
    var colorAll = {
        "point": sgworld.cesium.Color.fromCssColorString('#ff0000'),
        "polyline": sgworld.cesium.Color.fromCssColorString('#ffff00')
    };
    sgworld._Viewer.scene.globe.depthTestAgainstTerrain = true;
    var spaceD_polyline = sgworld.Command.execute(0, 10, colorAll, function () {
        sgworld._Viewer.scene.globe.depthTestAgainstTerrain = false;
    });
}
//水平距离测量
function MeasurementHD() {
    var colorAll = {
        "point": sgworld.cesium.Color.fromCssColorString('#ff0000'),
        "polyline": sgworld.cesium.Color.fromCssColorString('#ffff00')
    };
    sgworld._Viewer.scene.globe.depthTestAgainstTerrain = true;
    var spaceD_polyline = sgworld.Command.execute(0, 2, colorAll, function () {
        sgworld._Viewer.scene.globe.depthTestAgainstTerrain = false;
    });
}
//$("#labelDraw").click(function () {
//    alert("qq");
//})
//画文本
function labelDraw() {
    var Viewer = sgworld._Viewer;
    var handel;
    if (handel) {
        sgworld.DetachEventAll(handel);
    }
    //开启深度检测
    sgworld._Viewer.scene.globe.depthTestAgainstTerrain = true;
    //绑定左键单击事件
    handel = sgworld.AttachEvent('OnLButtonClk', function (x, y, movement) {
        var cartesian = Viewer.scene.pickPosition(movement.position);
        var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        var longitude = Cesium.Math.toDegrees(cartographic.longitude);
        var latitude = Cesium.Math.toDegrees(cartographic.latitude);
        var height = cartographic.height;

        //添加文本标签
        var position = sgworld.Creator.CreatePosition(longitude, latitude, height, 1, 0, 0, 0, 300);
        var label = sgworld.Creator.CreateLabel(position, "文本标签", '', {}, "0", '文本标签');

        //移除事件
        sgworld.DetachEventAll(handel);
        //关闭深度检测
        sgworld._Viewer.scene.globe.depthTestAgainstTerrain = false;
    });
}
//绘制线
function polylineDraw() {
    sgworld.Command.execute(0, 0, "", function () {
    });
}
//画面
function polygonDraw() {
    sgworld.Command.execute(0, 1, "", function () {
    });
}
//画矩形
function rectangleDraw() {
    sgworld.Command.execute(1, 5, "", function () {
    });
}
//画圆
function circleDraw() {
    sgworld.Command.execute(1, 6, "", function () {
    });
}
//体
var parentLayer = parent.layer;
//var tooltip = parent.TooltipCesium;
var clickNum = 0;
if (!parent.draw3DGraphic) {
    parent.draw3DGraphic = {
        cuboid: [],   //长方体
        cylinder: [],   //圆柱
        tapered: [],  //圆锥
        ball: [],      //球
        polyhedron: [] //多面体
    };
}
var draw3DGraphic = parent.draw3DGraphic;
if (!parent.edit3DGraphic) {
    parent.edit3DGraphic = {
        entity: null,
        graphic: null,
        fillColor: null,
        alpha: null,
        outlineColor: null
    };
}
var editGraphic = parent.edit3DGraphic;
var handle = null;
if (!parent.rightPick3DGraphicListener) {
    parent.rightPick3DGraphicListener = null;
}
//根据两点经纬度测算距离
function getGreatCircleDistance(lat1, lng1, lat2, lng2) {
    var radLat1 = getRad(lat1);
    var radLat2 = getRad(lat2);
    var EARTH_RADIUS = 6378137.0;

    var a = radLat1 - radLat2;
    var b = getRad(lng1) - getRad(lng2);

    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000.0;
    return s;
}

function getRad(d) {
    return d * Math.PI / 180.0;
}

//随机id
function createRandomId() {
    return (Math.random() * 10000000).toString(16).substr(0, 4) + '-' + (new Date()).getTime() + '-' + Math.random().toString().substr(2, 5);
}
//创建长方体
function createCuboid(callback) {
    var firstPoint = null;
    var size = [0, 0, 0];
    if (handle) {
        handle.destroy();
        handle = null;
    }
    if (clickNum !== 0) {
        clickNum = 0;
    }
    window.sgworld.ProjectTree.starttemporaryItem();

    handle = new Cesium.ScreenSpaceEventHandler(Viewer.scene.canvas);
   setHandler(handle);
    var cuboid = null;
    //鼠标左键单击
    handle.setInputAction(function (movement) {
        var degrees = sgworld.Navigate.getMouseDegrees(movement);
        if (!degrees) return;
        if (clickNum === 0) {
            firstPoint = { lon: degrees.lon, lat: degrees.lat, height: degrees.height };
            cuboid = Viewer.entities.add({
                id: createRandomId(),//获取随机ID
                name: "新建立方体",
                //position: _this._cesium.Cartesian3.fromDegrees(position[0], position[1], position[1]),
                position: Cesium.Cartesian3.fromDegrees(firstPoint.lon, firstPoint.lat, firstPoint.height),
                box: {
                    dimensions: new Cesium.Cartesian3(0, 0, 0),
                    material: new Cesium.ImageMaterialProperty({
                        image: null,
                        repeat: new Cesium.Cartesian2(1, 1),
                        color: Cesium.Color.RED.withAlpha(0.9)
                    }),
                    //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    fill: true,
                    outline: true,
                    outlineColor: Cesium.Color.RED,
                    shadows: Cesium.ShadowMode.ENABLED,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000000000)
                }
            });
            cuboid.box.dimensions = new Cesium.CallbackProperty(dimensions, false);
            window.sgworld.ProjectTree.pushtemporaryItem(cuboid);
            clickNum++;
        } else {
            clickNum = 0;
            tooltip.setVisible(false);
            handle.destroy();
            cuboid.geometryName = '立方体';
            draw3DGraphic.cuboid.push(cuboid);
            (typeof callback === "function") && callback(cuboid);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    //鼠标移动
    handle.setInputAction(function (movement) {
        if (clickNum === 0) {
            tooltip.showAt(movement.endPosition, "点击开始绘制第一个点");
            return;
        } else {
            tooltip.showAt(movement.endPosition, "再次点击结束绘制");
        }
        var degrees = sgworld.Navigate.getMouseDegrees(movement);
        if (!degrees) return;
        var long = getGreatCircleDistance(firstPoint.lat, firstPoint.lon, firstPoint.lat, degrees.lon);
        var width = getGreatCircleDistance(firstPoint.lat, firstPoint.lon, degrees.lat, firstPoint.lon);
        var center = {
            lon: (firstPoint.lon + degrees.lon) / 2,
            lat: (firstPoint.lat + degrees.lat) / 2
        };
        if (size) {
            size[0] = long;
            size[1] = width;
            size[2] = long > width ? width / 2 : long / 2;
        }
        cuboid.position = Cesium.Cartesian3.fromDegrees(center.lon, center.lat, firstPoint.height + size[2] / 2);
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    //动态绘制长方体
    function dimensions() {
        return Cesium.Cartesian3.fromArray(size);
    }
}

//创建圆柱
function createCylinder(callback) {
    var cylinder = null;
    var firstPoint = null;
    var radius = 0;
    if (handle) {
        handle.destroy();
        handle = null;
    }
    if (clickNum !== 0) {
        clickNum = 0;
    }
    window.sgworld.ProjectTree.starttemporaryItem();
    handle = new Cesium.ScreenSpaceEventHandler(Viewer.scene.canvas);
   setHandler(handle);
    //鼠标左键单击
    handle.setInputAction(function (movement) {
        var cartesian;
        var ray = Viewer.scene.camera.getPickRay(movement.position);
        if (ray) {
            cartesian = Viewer.scene.globe.pick(ray, Viewer.scene);
        }
        var feature = Viewer.scene.pick(movement.position);
        if (feature && feature.id !== cylinder) {
            var _cartesian = Viewer.scene.pickPosition(movement.position);
            if (_cartesian) {
                cartesian = _cartesian;
            }
        }
        if (!cartesian) {
            return;
        }
        var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        var longitude = Cesium.Math.toDegrees(cartographic.longitude);
        var latitude = Cesium.Math.toDegrees(cartographic.latitude);
        if (clickNum === 0) {
            firstPoint = { lon: longitude, lat: latitude, height: cartographic.height };
            cylinder = Viewer.entities.add({
                id: createRandomId(),//获取随机ID
                name: "新建圆柱体",
                position: Cesium.Cartesian3.fromDegrees(firstPoint.lon, firstPoint.lat, firstPoint.height),
                cylinder: {
                    length: 0,
                    topRadius: 0,
                    bottomRadius: 0,
                    material: new Cesium.ImageMaterialProperty({
                        image: null,
                        repeat: new Cesium.Cartesian2(1, 1),
                        color: Cesium.Color.RED.withAlpha(0.9)
                    }),
                    //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    fill: true,
                    shadows: Cesium.ShadowMode.ENABLED,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000000000),
                    outline: true,
                    outlineColor: Cesium.Color.RED
                }
            });
            cylinder.cylinder.length = new Cesium.CallbackProperty(getRadius, false);
            cylinder.cylinder.topRadius = new Cesium.CallbackProperty(getRadius, false);
            cylinder.cylinder.bottomRadius = new Cesium.CallbackProperty(getRadius, false);
            window.sgworld.ProjectTree.pushtemporaryItem(cylinder);
            clickNum++;
        } else {
            clickNum = 0;
            tooltip.setVisible(false);
            handle.destroy();
            cylinder.geometryName = '圆柱体';
            draw3DGraphic.cylinder.push(cylinder);
            (typeof callback === "function") && callback(cylinder);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    //鼠标移动
    handle.setInputAction(function (movement) {
        if (clickNum === 0) {
            tooltip.showAt(movement.endPosition, "点击开始绘制第一个点");
            return;
        } else {
            tooltip.showAt(movement.endPosition, "再次点击结束绘制");
        }
        var cartesian;
        var ray = Viewer.scene.camera.getPickRay(movement.endPosition);
        if (ray) {
            cartesian = Viewer.scene.globe.pick(ray, Viewer.scene);
        }
        var feature = Viewer.scene.pick(movement.endPosition);
        if (feature && feature.id !== cylinder) {
            var _cartesian = Viewer.scene.pickPosition(movement.endPosition);
            if (_cartesian) {
                cartesian = _cartesian;
            }
        }
        if (!cartesian) {
            return;
        }
        var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        var longitude = Cesium.Math.toDegrees(cartographic.longitude);
        var latitude = Cesium.Math.toDegrees(cartographic.latitude);
        radius = getGreatCircleDistance(firstPoint.lat, firstPoint.lon, latitude, longitude);
        cylinder.position = Cesium.Cartesian3.fromDegrees(firstPoint.lon, firstPoint.lat, firstPoint.height + radius / 2);
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    //动态绘制圆柱
    function getRadius() {
        return radius;
    }
}

//创建圆锥
function createTapered(callback) {
    var tapered = null;
    var firstPoint = null;
    var radius = 0;
    if (handle) {
        handle.destroy();
        handle = null;
    }
    if (clickNum !== 0) {
        clickNum = 0;
    }
    window.sgworld.ProjectTree.starttemporaryItem();
    handle = new Cesium.ScreenSpaceEventHandler(Viewer.scene.canvas);
   setHandler(handle);
    //鼠标左键单击
    handle.setInputAction(function (movement) {
        var cartesian;
        var ray = Viewer.scene.camera.getPickRay(movement.position);
        if (ray) {
            cartesian = Viewer.scene.globe.pick(ray, Viewer.scene);
        }
        var feature = Viewer.scene.pick(movement.position);
        if (feature && feature.id !== tapered) {
            var _cartesian = Viewer.scene.pickPosition(movement.position);
            if (_cartesian) {
                cartesian = _cartesian;
            }
        }
        if (!cartesian) {
            return;
        }
        var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        var longitude = Cesium.Math.toDegrees(cartographic.longitude);
        var latitude = Cesium.Math.toDegrees(cartographic.latitude);
        if (clickNum === 0) {
            firstPoint = { lon: longitude, lat: latitude, height: cartographic.height };
            tapered = Viewer.entities.add({
                id: createRandomId(),//获取随机ID
                name: "新建圆锥体",
                position: Cesium.Cartesian3.fromDegrees(firstPoint.lon, firstPoint.lat, firstPoint.height),
                cylinder: {
                    length: 0,
                    topRadius: 0,
                    bottomRadius: 0,
                    material: new Cesium.ImageMaterialProperty({
                        image: null,
                        repeat: new Cesium.Cartesian2(1, 1),
                        color: Cesium.Color.RED.withAlpha(0.9)
                    }),
                    //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    fill: true,
                    shadows: Cesium.ShadowMode.ENABLED,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000000000),
                    outline: true,
                    outlineColor: Cesium.Color.RED
                }
            });
            tapered.cylinder.length = new Cesium.CallbackProperty(getRadius, false);
            tapered.cylinder.bottomRadius = new Cesium.CallbackProperty(getRadius, false);
            window.sgworld.ProjectTree.pushtemporaryItem(tapered);
            clickNum++;
        } else {
            clickNum = 0;
            tooltip.setVisible(false);
            handle.destroy();
            tapered.geometryName = '圆锥体';
            draw3DGraphic.tapered.push(tapered);
            (typeof callback === "function") && callback(tapered);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    //鼠标移动
    handle.setInputAction(function (movement) {
        if (clickNum === 0) {
            tooltip.showAt(movement.endPosition, "点击开始绘制第一个点");
            return;
        } else {
            tooltip.showAt(movement.endPosition, "再次点击结束绘制");
        }
        var cartesian;
        var ray = Viewer.scene.camera.getPickRay(movement.endPosition);
        if (ray) {
            cartesian = Viewer.scene.globe.pick(ray, Viewer.scene);
        }
        var feature = Viewer.scene.pick(movement.endPosition);
        if (feature && feature.id !== tapered) {
            var _cartesian = Viewer.scene.pickPosition(movement.endPosition);
            if (_cartesian) {
                cartesian = _cartesian;
            }
        }
        if (!cartesian) {
            return;
        }
        var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        var longitude = Cesium.Math.toDegrees(cartographic.longitude);
        var latitude = Cesium.Math.toDegrees(cartographic.latitude);
        radius = getGreatCircleDistance(firstPoint.lat, firstPoint.lon, latitude, longitude);
        tapered.position = Cesium.Cartesian3.fromDegrees(firstPoint.lon, firstPoint.lat, firstPoint.height + radius / 2)
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    //动态绘制圆锥
    function getRadius() {
        return radius;
    }
}

//创建球
function createBall(callback) {
    var ball = null;
    var firstPoint = null;
    var radiusArr = [0, 0, 0];
    if (handle) {
        handle.destroy();
        handle = null;
    }
    if (clickNum !== 0) {
        clickNum = 0;
    }
    window.sgworld.ProjectTree.starttemporaryItem();
    handle = new Cesium.ScreenSpaceEventHandler(Viewer.scene.canvas);
   setHandler(handle);
    //鼠标左键单击
    handle.setInputAction(function (movement) {
        var cartesian;
        var ray = Viewer.scene.camera.getPickRay(movement.position);
        if (ray) {
            cartesian = Viewer.scene.globe.pick(ray, Viewer.scene);
        }
        var feature = Viewer.scene.pick(movement.position);
        if (feature && feature.id !== ball) {
            var _cartesian = Viewer.scene.pickPosition(movement.position);
            if (_cartesian) {
                cartesian = _cartesian;
            }
        }
        if (!cartesian) {
            return;
        }
        var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        var longitude = Cesium.Math.toDegrees(cartographic.longitude);
        var latitude = Cesium.Math.toDegrees(cartographic.latitude);
        if (clickNum === 0) {
            firstPoint = { lon: longitude, lat: latitude, height: cartographic.height };
            ball = Viewer.entities.add({
                id: createRandomId(),//获取随机ID
                name: "新建球体",
                position: Cesium.Cartesian3.fromDegrees(firstPoint.lon, firstPoint.lat, firstPoint.height),
                ellipsoid: {
                    radii: new Cesium.Cartesian3(0, 0, 0),
                    material: new Cesium.ImageMaterialProperty({
                        image: null,
                        repeat: new Cesium.Cartesian2(1, 1),
                        color: Cesium.Color.RED.withAlpha(0.9)
                    }),
                    //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    fill: true,
                    shadows: Cesium.ShadowMode.ENABLED,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000000000),
                    outline: true,
                    outlineColor: Cesium.Color.RED
                }
            });
            ball.ellipsoid.radii = new Cesium.CallbackProperty(getRadius, false);
            window.sgworld.ProjectTree.pushtemporaryItem(ball);
            clickNum++;
        } else {
            clickNum = 0;
            tooltip.setVisible(false);
            handle.destroy();
            ball.ellipsoid.radii = Cesium.Cartesian3.fromArray(radiusArr);
            ball.geometryName = '球体';
            draw3DGraphic.ball.push(ball);
            (typeof callback === "function") && callback(ball);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    //鼠标移动
    handle.setInputAction(function (movement) {
        if (clickNum === 0) {
            tooltip.showAt(movement.endPosition, "点击开始绘制第一个点");
            return;
        } else {
            tooltip.showAt(movement.endPosition, "再次点击结束绘制");
        }
        var cartesian;
        var ray = Viewer.scene.camera.getPickRay(movement.endPosition);
        if (ray) {
            cartesian = Viewer.scene.globe.pick(ray, Viewer.scene);
        }
        var feature = Viewer.scene.pick(movement.endPosition);
        if (feature && feature.id !== ball) {
            var _cartesian = Viewer.scene.pickPosition(movement.endPosition);
            if (_cartesian) {
                cartesian = _cartesian;
            }
        }
        if (!cartesian) {
            return;
        }
        var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        var longitude = Cesium.Math.toDegrees(cartographic.longitude);
        var latitude = Cesium.Math.toDegrees(cartographic.latitude);
        var radius = getGreatCircleDistance(firstPoint.lat, firstPoint.lon, latitude, longitude);
        ball.position = Cesium.Cartesian3.fromDegrees(firstPoint.lon, firstPoint.lat, firstPoint.height + radius);
        if (radiusArr) {
            radiusArr[0] = radiusArr[1] = radiusArr[2] = radius;
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    //动态绘制球
    function getRadius() {
        return Cesium.Cartesian3.fromArray(radiusArr);
    }
}

//创建多面体
function createPolyhedron(callback) {
    var polyhedron = null;
    var hierarchy = [];
    if (handle) {
        handle.destroy();
        handle = null;
    }
    if (clickNum !== 0) {
        clickNum = 0;
    }
    window.sgworld.ProjectTree.starttemporaryItem();
    handle = new Cesium.ScreenSpaceEventHandler(Viewer.scene.canvas);
   setHandler(handle);
    //鼠标左键单击
    handle.setInputAction(function (movement) {
        var cartesian;
        var ray = Viewer.scene.camera.getPickRay(movement.position);
        if (ray) {
            cartesian = Viewer.scene.globe.pick(ray, Viewer.scene);
        }
        var feature = Viewer.scene.pick(movement.position);
        if (feature && feature.id !== polyhedron) {
            var _cartesian = Viewer.scene.pickPosition(movement.position);
            if (_cartesian) {
                cartesian = _cartesian;
            }
        }
        if (!cartesian) {
            return;
        }
        var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        var longitude = Cesium.Math.toDegrees(cartographic.longitude);
        var latitude = Cesium.Math.toDegrees(cartographic.latitude);
        hierarchy.push(longitude, latitude, cartographic.height);
        if (clickNum === 0) {
            hierarchy.push(longitude, latitude, cartographic.height);
        } else if (clickNum === 1) {
            var height = getGreatCircleDistance(hierarchy[0], hierarchy[1], hierarchy[3], hierarchy[4]);
            polyhedron = Viewer.entities.add({
                id: createRandomId(),//获取随机ID
                name: "新建多边体",
                polygon: {
                    hierarchy: new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArrayHeights(hierarchy)),
                    material: new Cesium.ImageMaterialProperty({
                        image: null,
                        repeat: new Cesium.Cartesian2(1, 1),
                        color: Cesium.Color.RED.withAlpha(0.9)
                    }),
                    //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    extrudedHeight: hierarchy[2] + height,
                    fill: true,
                    shadows: Cesium.ShadowMode.ENABLED,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000000000),
                    outline: true,
                    outlineColor: Cesium.Color.RED,
                    height: hierarchy[2]
                }
            });
            polyhedron.polygon.hierarchy = new Cesium.CallbackProperty(getHierarchy, false);
            window.sgworld.ProjectTree.pushtemporaryItem(polyhedron);
        }
        clickNum++;
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    //鼠标移动
    handle.setInputAction(function (movement) {
        if (clickNum === 0) {
            tooltip.showAt(movement.endPosition, "左键点击开始绘制点");
            return;
        } else if (clickNum === 1) {
            tooltip.showAt(movement.endPosition, "点击添加第二个点");
        } else {
            tooltip.showAt(movement.endPosition, "右键结束绘制");
        }
        var cartesian;
        var ray = Viewer.scene.camera.getPickRay(movement.endPosition);
        if (ray) {
            cartesian = Viewer.scene.globe.pick(ray, Viewer.scene);
        }
        var feature = Viewer.scene.pick(movement.endPosition);
        if (feature && feature.id !== polyhedron) {
            var _cartesian = Viewer.scene.pickPosition(movement.endPosition);
            if (_cartesian) {
                cartesian = _cartesian;
            }
        }
        if (!cartesian) {
            return;
        }
        var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        var longitude = Cesium.Math.toDegrees(cartographic.longitude);
        var latitude = Cesium.Math.toDegrees(cartographic.latitude);
        hierarchy.splice(hierarchy.length - 3, 3);
        hierarchy.push(longitude, latitude, cartographic.height);
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    //鼠标右键单击结束绘制
    handle.setInputAction(function (movement) {
        tooltip.setVisible(false);
        handle.destroy();
        if (clickNum < 2) {
            clickNum = 0;
            return;
        }
        clickNum = 0;
        polyhedron.geometryName = '多边体';
        draw3DGraphic.polyhedron.push(polyhedron);
        (typeof callback === "function") && callback(polyhedron);
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

    //动态绘制球
    function getHierarchy() {
        return new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArrayHeights(hierarchy));
    }
}

//绘制立方体
function boxDraw() {
    //parent.setDepthTest('open');
    //parent.removeMovePickEvent();
    createCuboid(function (cuboid) {
        editGraphic.entity = cuboid;
        editGraphic.graphic = cuboid.box;
        editGraphic.fillColor = '#ff0000';
        editGraphic.alpha = 90;
        editGraphic.outLineColor = '#ff0000';

        var parentId = window.sgworld.ProjectTree.findItem("绘制对象");
        if (parentId == "") {
            parentId = window.sgworld.ProjectTree.createGroup("绘制对象", true, 0);
        }
        var pId = window.sgworld.ProjectTree.createGroup("三维物体", true, parentId);
        window.sgworld.ProjectTree.insertProjectTree(pId, "立方体", cuboid.name, window.sgworld.ProjectTree.exitsObjectType.box, cuboid, true);
        //跳转到属性页面
        //parent.fnPropsOpen('三维·立方体属性', 'components/Plotting/ThreeDimensionalAttribute', 350, 540, 2, '');
        window.sgworld.ProjectTree.endtemporaryItem();
        //parent.createMovePickEvent();
        //parent.setDepthTest('close');
    });
};
//绘制圆柱
function cylinderDraw() {
    //parent.setDepthTest('open');
    //parent.removeMovePickEvent();
    createCylinder(function (cylinder) {
        editGraphic.entity = cylinder;
        editGraphic.graphic = cylinder.cylinder;
        editGraphic.fillColor = '#ff0000';
        editGraphic.alpha = 90;
        editGraphic.outLineColor = null;
        //跳转到属性页面
        //parent.fnPropsOpen('三维·圆柱体属性', 'components/Plotting/ThreeDimensionalAttribute', 350, 540, 2, '');
        window.sgworld.ProjectTree.endtemporaryItem();
        var parentId = window.sgworld.ProjectTree.findItem("绘制对象");
        if (parentId == "") {
            parentId = window.sgworld.ProjectTree.createGroup("绘制对象", true, 0);
        }
        var pId = window.sgworld.ProjectTree.createGroup("三维物体", true, parentId);
        window.sgworld.ProjectTree.insertProjectTree(pId, "圆柱", cylinder.name, window.sgworld.ProjectTree.exitsObjectType.cone, cylinder, true);
        window.sgworld.ProjectTree.endtemporaryItem();
        //parent.createMovePickEvent();
        //parent.setDepthTest('close');
    });
};
//绘制圆锥
function coneDraw() {
    //parent.setDepthTest('open');
    //parent.removeMovePickEvent();
    createTapered(function (tapered) {
        editGraphic.entity = tapered;
        editGraphic.graphic = tapered.cylinder;
        editGraphic.fillColor = '#ff0000';
        editGraphic.alpha = 90;
        editGraphic.outLineColor = null;
        var parentId = window.sgworld.ProjectTree.findItem("绘制对象");
        if (parentId == "") {
            parentId = window.sgworld.ProjectTree.createGroup("绘制对象", true, 0);
        }
        var pId = window.sgworld.ProjectTree.createGroup("三维物体", true, parentId);
        window.sgworld.ProjectTree.insertProjectTree(pId, "圆锥", tapered.name, window.sgworld.ProjectTree.exitsObjectType.cone, tapered, true);
        //跳转到属性页面
        //parent.fnPropsOpen('三维·圆锥体属性', 'components/Plotting/ThreeDimensionalAttribute', 350, 540, 2, '');
        window.sgworld.ProjectTree.endtemporaryItem();
        //parent.createMovePickEvent();
        //parent.setDepthTest('close');
    });
};
//绘制球体
function circleDraw() {
    //parent.setDepthTest('open');
    //parent.removeMovePickEvent();
    createBall(function (ball) {
        editGraphic.entity = ball;
        editGraphic.graphic = ball.ellipsoid;
        editGraphic.fillColor = '#ff0000';
        editGraphic.alpha = 90;
        editGraphic.outLineColor = null;
        //跳转到属性页面
        //parent.fnPropsOpen('三维·球体属性', 'components/Plotting/ThreeDimensionalAttribute', 350, 540, 2, '');
        window.sgworld.ProjectTree.endtemporaryItem();
        var parentId = window.sgworld.ProjectTree.findItem("绘制对象");
        if (parentId == "") {
            parentId = window.sgworld.ProjectTree.createGroup("绘制对象", true, 0);
        }
        var pId = window.sgworld.ProjectTree.createGroup("三维物体", true, parentId);
        window.sgworld.ProjectTree.insertProjectTree(pId, "球", ball.name, window.sgworld.ProjectTree.exitsObjectType.ellipsoid, ball, true);
        window.sgworld.ProjectTree.endtemporaryItem();
        //parent.createMovePickEvent();
        //parent.setDepthTest('close');
    });

};

//绘制多面体
function multilateralDraw() {
    //parent.setDepthTest('open');
    //parent.removeMovePickEvent();
    createPolyhedron(function (polyhedron) {
        console.log(polyhedron);
        editGraphic.entity = polyhedron;
        editGraphic.graphic = polyhedron.polygon;
        editGraphic.fillColor = '#ff0000';
        editGraphic.alpha = 90;
        editGraphic.outLineColor = '#ff0000';
        var parentId = window.sgworld.ProjectTree.findItem("绘制对象");
        if (parentId == "") {
            parentId = window.sgworld.ProjectTree.createGroup("绘制对象", true, 0);
        }
        var pId = window.sgworld.ProjectTree.createGroup("三维物体", true, parentId);
        window.sgworld.ProjectTree.insertProjectTree(pId, "多面体", polyhedron.name, window.sgworld.ProjectTree.exitsObjectType.polygon, polyhedron, true);
        //跳转到属性页面
        //parent.fnPropsOpen('三维·多边体属性', 'components/Plotting/ThreeDimensionalAttribute', 350, 540, 2, '');
        window.sgworld.ProjectTree.endtemporaryItem();
        //parent.createMovePickEvent();
        //parent.setDepthTest('close');
    });

};
//关闭标绘
function closeScene() {
    var main = document.getElementById("kzmb");
    main.style.display = "none";
}
/**
 * 添加左键绑定事件
 */
function setHandler(handler) {
    try {
        if (btnHandler) {
            btnHandler.destroy();
            $('.twipsy').hide();
            TooltipCesium.setVisible(false);
        }
        if (PrimitiveArr.length > 0) {
            for (i in PrimitiveArr) {
                PrimitiveArr[i].destroy();
            }
        }
        btnHandler = handler;
        PrimitiveArr = [];
    } catch (ex) {
    }
}

var tooltip = (function () {
    var isInit = false;
    var viewer;
    var labelEntity;
    var eyeOffset_Z = 0;

    function _() {
    };

    _.initTool = function (_viewer) {
        if (isInit) {
            return;
        }
        viewer = _viewer;
        var div = document.createElement('DIV');
        div.id = "TooltipCesium";
        div.style.cssText = "display: none;position: absolute;pointer-events: none;min-width: 100px;padding: 1px 1px 1px 18px;font-size: 11px;z-index: 1000;opacity: 0.8;background-color: rgba(0,0,0,0.7);border-radius: 3px;";

        var title = document.createElement('span');
        title.style.cssText = 'font-family:黑体;color:white;font-weight: bolder;font-size: 14px;';
        div.appendChild(title);

        this._div = div;
        this._title = title;

        // add to frame div and display coordinates
        viewer.container.appendChild(div);
        isInit = true;
    }

    _.setVisible = function (visible) {
        if (!isInit) {
            return;
        }
        this._div.style.display = visible ? 'block' : 'none';
    };

    /*
    position屏幕坐标
    显示在椭球面
    */
    _.showAt = function (position, message) {
        if (!isInit) {
            return;
        }
        if (position && message) {
            this.setVisible(true);
            this._title.innerHTML = message;
            this._div.style.left = position.x + 5 + "px";
            this._div.style.top = (position.y - this._div.clientHeight / 2) - 5 + "px";
        }
    };

    /*
    cartesian世界坐标
    显示在真实位置
    */
    _.showAtCartesian = function (cartesian, message) {
        if (!isInit) {
            return;
        }
        if (cartesian && message) {
            var CanvasCoordinates = viewer.scene.cartesianToCanvasCoordinates(cartesian);
            this.setVisible(true);
            this._title.innerHTML = message;
            this._div.style.left = CanvasCoordinates.x + 5 + "px";
            this._div.style.top = (CanvasCoordinates.y - this._div.clientHeight / 2) - 5 + "px";
        }
    };
    return _;
})();
//修改
var fnFlag;
var mObj;
//定义操作面板的位置全局变量
var fLeft;
var fTop;
var fPosi;
//定义属性面板的位置全局变量
var pLeft;
var pTop;
var pPosi;
//定义图层面板的位置全局变量
var lLeft;
var lTop;
var lPosi;

//定义属性框 图层框 操作面板框 测量结果 tooltip框
var indexProp;
var indexLayer
var indexFunc
var indexRes
var indexTipEdit

//选择数据源弹出框的index
var selDataIndex;

//定义是否触发自适应高度方法的变量
var autoH = false;
//定义最近一次操作的页面数据对象
var lastFuncObj = {};
var lastPropObj = {};

//定义弹出tip的类型
var TipEditType;
var cEditType = '';
var isPhone = null;
//图层面板弹出框方法
function fnLevelOpen(title, url, width, height) {
    //手机端模式
    if (isPhone) {
        layer.closeAll();
        url = './' + url + '.html';
        indexLayer = layer.open({
            skin: 'layerPhoneCss fadeInLeft',
            type: 2,
            title: '图层',
            area: ['100%', '100%'],
            fixed: false, //不固定
            shadeClose: false,
            resize: false,
            content: url,
            anim: -1,
            cancel: function (index, obj) {
            },
            success: function (obj) {
                obj.find('iframe').contents().find('body').css({ 'height': '100%', 'overflow': 'hidden' });
                obj.find('iframe').contents().find('#treeDemo').css({ 'height': '100%', 'overflow': 'hidden' });
                if (obj.find('iframe')[0].contentWindow.scrollStart && typeof obj.find('iframe')[0].contentWindow.scrollStart == 'function') {
                    obj.find('iframe')[0].contentWindow.scrollStart();
                }
            }
        });
        return;
    }
    //pc端模式
    var left;
    var anim;
    var cls;
    console.log(width)
    lLeft = parseInt(lLeft);
    lTop = parseInt(lTop);
    if (lPosi == 'left') {
        left = lLeft + 65;
        cls = 'fadeInLeft'
    } else {
        left = lLeft - width - 30;
        cls = 'fadeInRight'
    }
    if (!document.getElementById('slider') && parent.document.getElementById('slider')) {
        left = parent.window.innerWidth + lLeft - width - 65;
        cls = 'fadeInRight';
    }
    var $title = $('#layui-layer' + indexLayer).find('.layui-layer-title');
    if ($title.length > 0 && $title.text() == '图层') {
        $('#layui-layer' + indexLayer).css({
            'top': lTop,
            'left': left,
        });
        $('#layui-layer' + indexLayer).show();
    } else {
        if (indexLayer) {
            layer.close(indexLayer);
            $('#layui-layer' + indexLayer).find('iframe').contents().find('body').mCustomScrollbar("destroy")
        }
        //iframe层-父子操作
        indexLayer = layer.open({
            skin: 'other-class ' + cls,
            type: 2,
            title: '图层',
            area: ['350px', '500px'],
            fixed: false, //不固定
            shadeClose: false,
            resize: false,
            content: url,
            offset: [lTop, left],
            anim: -1,
            cancel: function (index, obj) {
                //判断是否存在右键菜单等
                var $obj = obj.find('iframe').contents();
                $obj.find('#newAndUpdateInput').length > 0 ? $obj.find('#newAndUpdateInput').hide() : '';
                $obj.find('#rMenu').length > 0 ? $obj.find('#rMenu').hide() : '';
                obj.hide();
                return false;
            },
            success: function (obj) {
                obj.find('iframe').contents().find('body').css({ 'height': height - 30, 'overflow': 'hidden' });
                obj.find('iframe').contents().find('#treeDemo').css({ 'height': height - 40, 'overflow': 'hidden' });
                if (obj.find('iframe')[0].contentWindow.scrollStart && typeof obj.find('iframe')[0].contentWindow.scrollStart == 'function') {
                    obj.find('iframe')[0].contentWindow.scrollStart();
                }
            }
        });
    }
}

//图层控制
function createLayercontrol() {
    fnLevelOpen("图层", "../../SmartEarthSDK/Workers/layer/layer.html", "350", "500");
}